﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Collections;
using System.Data;
using System.Windows;
using System.ComponentModel;
using System.Xml.Serialization;
using MockupDesigner.AppItems;
using MockupDesigner.Editors.ValidableEditors;
using MockupDesigner.Items.Grid;
using Microsoft.Windows.Controls;

namespace MockupDesigner.Items
{
    [DataGridEditor]
    public class DataGridItem : ResizableItem
    {
        public static readonly DependencyProperty HeadersVisibilityProperty =
          DependencyProperty.Register("HeadersVisibility", typeof(DataGridHeadersVisibility), typeof(DataGridItem));

        public DataGridHeadersVisibility HeadersVisibility
        {
            get { return (DataGridHeadersVisibility)GetValue(HeadersVisibilityProperty); }
            set
            {
                SetValue(HeadersVisibilityProperty, value);
            }
        }

        [Category("Prop_General")]
        [DisplayName("Firts Line As Headers")]
        public bool FirstLineAsHeaders
        {
            get
            {
                return HeadersVisibility == DataGridHeadersVisibility.Column;
            }
            set
            {
                bool oldVal = FirstLineAsHeaders;
                if (value == oldVal)
                {
                    return;
                }
                OnPropertyChanging("FirstLineAsHeaders", oldVal, value);
                HeadersVisibility = value ? DataGridHeadersVisibility.Column : DataGridHeadersVisibility.None;
                ReloadItems();                
                OnPropertyChanged("FirstLineAsHeaders");
            }
        }

        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(DataGridItem));

        // Explicitly hidden property : non serializable
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public IEnumerable ItemsSource
        {
            get
            {
                return (IEnumerable)GetValue(ItemsSourceProperty);
            }
            set
            {
                SetValue(ItemsSourceProperty, value);
                this.autochanging = true;
                if (items.Count() > 0 && this.Parent is DesignerItem)
                    this.Height = 25 * items[0].Count();
                if (items[0].Count() > 0 && this.Parent is DesignerItem)
                    this.Width = 65 * items.Count();
                this.autochanging = false;
            }
        }

        private string[][] items;
        public string[][] Items
        {
            get 
            {
                string[][] tmpitems = new string[items.Length][];
                for( int i=0 ; i<items.Length;i++)
                {
                    tmpitems[i] = new string[items[i].Length];
                    for(int j= 0;j<items[i].Length;j++)
                    {
                        tmpitems[i][j] = string.IsNullOrEmpty(items[i][j]) ? DataGridHelper.EMPTY_CELL : items[i][j];
                    }
                }
                return tmpitems;
            }
            set
            {
                if (AreItemsEqual(items, value))
                {
                    return;
                }
                string[][] oldVal = items;
                items = value;
                OnPropertyChanging("Items", oldVal, value);
                ReloadItems();
                OnPropertyChanged("Items");
            }
        }

        private bool AreItemsEqual(string[][] items, string[][] value)
        {
            if (items == null && value == null)
                return true;
            if (items == null && value != null)
                return false;
            if (items != null && value == null)
                return false;
            if (items.Count() != value.Count())
            {
                return false;
            }
            if (items.Count() > 0)
            {
                if (items[0].Count() != value[0].Count())
                {
                    return false;
                }
                for (int i = 0; i < items.Count(); i++)
                {
                    for (int j = 0; j < items[0].Count(); j++)
                    {
                        if (items[i][j] != value[i][j])
                            return false;
                    }
                }
            }
            return true;
        }
        public override void EndInit()
        {
            base.EndInit();
            ReloadItems();
        }

        public DataGridItem()
        {
            string[][] init = new string[4][];
            for (int i = 0; i < init.Count(); i++)
            {
                init[i] = new string[5];
            }
            init[0][0] = "FirstName";
            init[1][0] = "LastName";
            init[2][0] = "Age";
            init[3][0] = "Admin?";

            init[0][1] = "Toto";
            init[1][1] = "Dupont";
            init[2][1] = "8";
            init[3][1] = DataGridHelper.VAL_TRUE;

            init[0][2] = "Alex";
            init[1][2] = "Durand";
            init[2][2] = "12";
            init[3][2] = DataGridHelper.VAL_FALSE;

            init[0][3] = "Nico";
            init[1][3] = "Pouet";
            init[2][3] = "34";
            init[3][3] = DataGridHelper.VAL_FALSE;

            init[0][4] = "Bart";
            init[1][4] = "Simp";
            init[2][4] = "45";
            init[3][4] = DataGridHelper.VAL_FALSE;

            this.Items = init;
        }

        public override Size GetPreferredSize()
        {
            return new Size(272, 122);
        }

        private void ReloadItems()
        {
            DataTable table = new DataTable();
            int columns = items.Count();
            if (columns > 0)
            {
                int rows = items[0].Count();
                int startIndex = FirstLineAsHeaders ? 1 : 0;

                for (int i = 0; i < columns; i++)
                {
                    DataColumn col = new DataColumn(startIndex == 1 ? items[i][0] : i.ToString(),
                        startIndex == 0 ? typeof(string) : DataGridHelper.GetColumnType(items[i]));
                    table.Columns.Add(col);
                }
                for (int i = startIndex; i < rows; i++)
                {
                    DataRow row = table.NewRow();
                    table.Rows.Add(row);
                    for (int j = 0; j < columns; j++)
                    {
                        table.Rows[table.Rows.Count - 1][j] = DataGridHelper.GetRealCellVal(items[j][i], table.Columns[j].DataType);
                    }
                }
            }
            else
            {
                DataColumn col = new DataColumn("", typeof(string));
                col.MaxLength = 100;
                table.Columns.Add(col);
            }
            this.ItemsSource = table.DefaultView;
        }
    }
}
